import fs from 'fs';
import express from 'express';
// import babelCore from "@babel/core";
import ts from "typescript";
import postcss from "postcss";
import postcssConfig from './postcss.config.js';
import tsconfig from './tsconfig.json';

const app = express();
const port = 3000;

app.get('/', (req, res) => {
  const content = fs.readFileSync('index.html');
  res.status(200).set('Content-Type', 'text/html').end(content);
});

app.get('*.css$', async (req, res) => {
  // console.log('css url', req.url);
  const content = fs.readFileSync(req.url.slice(1));
  const result = await postcss(postcssConfig.plugins).process(content, { from: req.url.slice(1), to: undefined });
  res.status(200).set('Content-Type', 'text/css').end(result.css);
});


app.get('*.ts$', async (req, res) => {
  const content = fs.readFileSync(req.url.slice(1), 'utf-8');
  res.status(200).set('Content-Type', 'application/javascript').end(compile(content));
});

app.get('*.js$', async (req, res) => {
  const content = fs.readFileSync(req.url.slice(1), 'utf-8');
  res.status(200).set('Content-Type', 'application/javascript').end(content);
});


app.get('*.ico$', async (req, res) => {
  const content = fs.readFileSync(req.url.slice(1));
  res.status(200).set('Content-Type', 'image/x-icon').end(content);
});


app.listen(port, () => {
  console.log(`App listening at http://localhost:${port}`);
});


function compile(source, options = tsconfig) {
  const result = ts.transpileModule(source, options);
  // console.log('result>>>>', result.outputText);
  return result.outputText;
}

/*function compile(source) {
  const result = babelCore.transformSync(source, {
    filename: 'file.ts'
  });
  return result.code;
}*/
